package com.skzh.framework.web.service;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.skzh.common.constant.CacheConstants;
import com.skzh.common.core.domain.entity.SysUser;
import com.skzh.common.core.redis.RedisCache;
import com.skzh.common.exception.user.UserPasswordNotMatchException;
import com.skzh.common.exception.user.UserPasswordRetryLimitExceedException;
import com.skzh.common.utils.SecurityUtils;
import com.skzh.framework.security.context.AuthenticationContextHolder;

/**
 * 登录密码方法
 *
 * @author skzh
 */
@Component
public class SysPasswordService {
    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount}" )
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}" )
    private int lockTime;

    @Value(value = "1" )
    private int timeout;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validate(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        //从缓存获取当前用户密码重试次数
        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        //如果重试次数超过配置的最大允许次数（maxRetryCount），则抛出密码重试次数超限异常。
        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        //检查用户提供的密码是否与数据库的密码匹配
        if (!matches(user, password)) {
            retryCount = retryCount + 1;
            //更新redis缓存里的重复次数，设置锁定时间 --- 键为pwd_err_cnt:username，值为retryCount ,锁定时间为lockTime,
            //这里说是锁定时间，但实际上还是缓存的过期时间机制。
            //输入错误的次数(如1或5),都会存储在redis里lockTime时长。
            //retryCount=5之前，每次新输错，retryCount都会+1并且更新过期时间，这时lockTime的意义还是缓存过期时间。当retryCount>=5时，上面就会抛出异常，这时候的lockTime就成了锁定时间。
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            //设置缓存的过期时间 1min
            //redisCache.expire(getCacheKey(username), timeout, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(SysUser user, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getCacheKey(loginName))) {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}
